<template>
  <n-grid cols="1" responsive="screen">
    <n-grid-item>
      <n-card title="Oracle数据库连接设置" class="mb-4">
        <n-form :label-width="80" :model="formValue" :rules="databaseRules" ref="databaseFormRef">
          <n-form-item label="主机地址" path="host">
            <n-input v-model:value="formValue.host" placeholder="例如：localhost" />
          </n-form-item>

          <n-form-item label="端口" path="port">
            <n-input-number
              v-model:value="formValue.port"
              placeholder="1521"
              :min="1"
              :max="65535"
            />
          </n-form-item>

          <n-form-item label="服务名" path="service_name">
            <n-input v-model:value="formValue.service_name" placeholder="例如：ORCL" />
          </n-form-item>

          <n-form-item label="用户名" path="username">
            <n-input v-model:value="formValue.username" placeholder="数据库用户名" />
          </n-form-item>

          <n-form-item label="密码" path="password">
            <n-input
              v-model:value="formValue.password"
              type="password"
              placeholder="数据库密码"
              show-password-on="click"
            />
          </n-form-item>

          <n-form-item>
            <n-space>
              <n-button type="info" @click="testConnection" :loading="testLoading">
                测试连接
              </n-button>
            </n-space>
          </n-form-item>
        </n-form>
      </n-card>

      <div>
        <n-space>
          <n-button type="primary" @click="formSubmit" :loading="loading"> 保存设置</n-button>
          <n-button @click="loadSettings"> 重置</n-button>
        </n-space>
      </div>
    </n-grid-item>
  </n-grid>
</template>

<script lang="ts" setup>
  import { reactive, ref, onMounted } from 'vue';
  import { useMessage } from 'naive-ui';
  import { invoke } from '@tauri-apps/api/core';

  interface DatabaseConfig {
    host: string;
    port: number;
    service_name: string;
    username: string;
    password: string;
  }

  const databaseRules = {
    host: {
      required: true,
      message: '请输入主机地址',
      trigger: 'blur',
    },
    port: {
      required: true,
      type: 'number',
      message: '请输入端口号',
      trigger: 'blur',
    },
    service_name: {
      required: true,
      message: '请输入服务名',
      trigger: 'blur',
    },
    username: {
      required: true,
      message: '请输入用户名',
      trigger: 'blur',
    },
    password: {
      required: true,
      message: '请输入密码',
      trigger: 'blur',
    },
  };

  const databaseFormRef: any = ref(null);
  const message = useMessage();
  const loading = ref(false);
  const testLoading = ref(false);

  const formValue = reactive<DatabaseConfig>({
    host: '',
    port: 1521,
    service_name: '',
    username: '',
    password: '',
  });

  // 加载数据库设置
  async function loadSettings() {
    try {
      const settings = await invoke<any>('get_user_settings');
      const dbConfig = settings.database || {
        host: '',
        port: 1521,
        service_name: '',
        username: '',
        password: '',
      };
      Object.assign(formValue, dbConfig);
      message.success('数据库设置加载成功');
    } catch (error) {
      console.error('加载数据库设置失败:', error);
      message.error('加载数据库设置失败');
    }
  }

  // 保存数据库设置
  async function saveSettings() {
    try {
      loading.value = true;

      // 获取当前设置
      const currentSettings = await invoke<any>('get_user_settings');

      const success = await invoke<boolean>('save_user_settings', {
        settings: {
          nickname: currentSettings.nickname || '',
          theme: currentSettings.theme || 'light',
          database: formValue, // 只更新统一的数据库配置
          auto_login: {
            environments: currentSettings.auto_login?.environments || {
              env_55: '',
              env_54: '',
              localhost: '',
            },
          },
          ai_settings: currentSettings.ai_settings || {
            api_key: '',
          },
        },
      });

      if (success) {
        message.success('数据库设置保存成功');
      } else {
        message.error('数据库设置保存失败');
      }
    } catch (error) {
      console.error('保存数据库设置失败:', error);
      message.error(`保存数据库设置失败: ${error}`);
    } finally {
      loading.value = false;
    }
  }

  // 测试数据库连接
  async function testConnection() {
    try {
      testLoading.value = true;
      const result = await invoke<string>('test_database_connection', {
        config: formValue,
      });
      message.success(result);
    } catch (error) {
      console.error('测试连接失败:', error);
      message.error(typeof error === 'string' ? error : '测试连接失败');
    } finally {
      testLoading.value = false;
    }
  }

  // 表单提交
  function formSubmit() {
    databaseFormRef.value.validate((errors: any) => {
      if (!errors) {
        saveSettings();
      } else {
        message.error('请填写完整信息');
      }
    });
  }

  // 组件挂载时加载设置
  onMounted(() => {
    loadSettings();
  });
</script>

<style lang="less" scoped>
  .n-form {
    max-width: 600px;
  }

  .mb-4 {
    margin-bottom: 16px;
  }
</style>
